package com.example.common.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

public class LocalDataRecordUtils {

    private static final String REFUSE_UPDATE_VERSION = "RefuseUpdateVersion";

    private final Context mContext;
    private final SharedPreferences mSharedPreferences;

    public LocalDataRecordUtils(Context context) {
        this.mContext = context;
        String FILE_NAME = "common-config";
        mSharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    }

    /**
     * 设置拒绝更新版本
     */
    public void setRefuseUpdateVersion(String version) {
        mSharedPreferences.edit().putString(REFUSE_UPDATE_VERSION, version).apply();
    }

    /**
     * 是否应该更新
     */
    public boolean isShouldUpdate() {
        String refuseUpdateVersion = mSharedPreferences.getString(REFUSE_UPDATE_VERSION, null);
        if (refuseUpdateVersion != null) {
            int oldVersion = Integer.parseInt(refuseUpdateVersion.replace(".", ""));
            int newVersion = Integer.parseInt(getVersionName(mContext).replace(".", ""));
            if (newVersion <= oldVersion) {
                return false;
            }
        }


        return true;
    }

    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
}
